import { Injectable } from '@nestjs/common';
import { CreateDepartmentDto } from './dto/create-department.dto';
import { UpdateDepartmentDto } from './dto/update-department.dto';
import { PrismaService } from '../prisma/prisma.service';
import { plainToInstance } from 'class-transformer';
import { ResponseDepartmentDto } from './dto/response-department.dto';

@Injectable()
export class DepartmentService {
  constructor(private prisma: PrismaService) {}

  async create(createDepartmentDto: CreateDepartmentDto) {
    const department = await this.prisma.department.create({
      data: {
        ...createDepartmentDto,
        createdBy: 'system',
        updatedBy: 'system',
      },
    });

    return plainToInstance(ResponseDepartmentDto, department);
  }

  async findAll() {
    const departments = await this.prisma.department.findMany({
      where: {
        deletedAt: null,
      },
    });
    return plainToInstance(ResponseDepartmentDto, departments);
  }

  findOne(id: number) {
    const department = this.prisma.department.findUnique({
      where: {
        id,
        deletedAt: null,
      },
    });
    return plainToInstance(ResponseDepartmentDto, department);
  }

  async update(id: number, updateDepartmentDto: UpdateDepartmentDto) {
    const department = await this.prisma.department.update({
      where: {
        id,
      },
      data: {
        ...updateDepartmentDto,
        updatedBy: 'system',
      },
    });

    return plainToInstance(ResponseDepartmentDto, department);
  }

  async remove(id: number) {
    await this.prisma.department.update({
      where: {
        id,
      },
      data: {
        deletedAt: new Date(),
      },
    });
    return plainToInstance(ResponseDepartmentDto, { id });
  }
}
